﻿using BCCommon;
using BCCommon.Enums;
using BCCommon.Enums.Driver;
using BCCommon.TMS.Driver;
using BCData.Common.Area;
using BCData.Common.IP;
using BCData.TMS.Agent.AgentAreaRecord;
using BCData.TMS.Agent.AgentRecord;
using BCData.TMS.Driver;
using BCData.TMS.LearningTrain;
using BCData.TMS.WorkingCompany;
using BCData.Website.User.User;
using BCDto.Common.IP;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.Driver;
using BCDto.TMS.Driver.Horseman;
using BCDto.TMS.Driver.VehicleBusiness;
using BCDto.Website.User;
using BCEntity.Common.Area;
using BCEntity.Common.EntityNameConst;
using BCEntity.Common.IP;
using BCEntity.TMS.Driver;
using BCEntity.TMS.LearningTrain.PendingLearningVehicle;
using BCEntity.Website.User;
using BCService.Common.Dictionary;
using BCService.TMS.Agent.AgentRecord;
using BCService.TMS.Fence;
using BCService.TMS.Insurance.PersonalInsuranceRecord;
using BCService.TMS.VehicleTypeService;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;

namespace BCService.TMS.Driver
{
    public class DriverService : IDriverService
    {
        private readonly IDriverData driverData;
        private readonly IProvinceData provinceData;
        private readonly ICityData cityData;
        private readonly ICountyData countyData;
        private readonly IUserData userData;
        private readonly IDatabaseContext databaseContext;
        private readonly IIPAddressRecordData ipAddressRecordData;
        private readonly IRedisService redisService;
        private readonly IAgentRecordData agentRecordData;
        private readonly IPendingLearningVehicleData pendingLearningTrainData;
        private readonly string key = string.Format("{0}", EntityNameConst.DriverEntity);
        private readonly string userKey = string.Format("{0}", EntityNameConst.UserEntity);
        private readonly string keyPendingLearningVehicle = string.Format("{0}", EntityNameConst.PendingLearningVehicleEntity);
        private readonly IWorkingCompanyData workingCompanyData;
        private readonly IAgentRecordService agentRecordService;
        private readonly IVehicleTypeService vehicleTypeService;
        private readonly IFenceService fenceService;
        private readonly IPersonalInsuranceRecordService personalInsuranceRecordService;
        private readonly IDictionaryReferenceService dictionaryService;
        private readonly IAgentAreaRecordData agentAreaRecordData;

        public DriverService(IDriverData driverData,
            IProvinceData provinceData,
            ICityData cityData,
            ICountyData countyData,
            IUserData userData,
            IDatabaseContext databaseContext,
            IIPAddressRecordData ipAddressRecordData,
            IRedisService redisService,
            IAgentRecordData agentRecordData,
            IPendingLearningVehicleData pendingLearningTrainData,
            IWorkingCompanyData workingCompanyData,
            IAgentRecordService agentRecordService,
            IVehicleTypeService vehicleTypeService,
            IFenceService fenceService,
            IPersonalInsuranceRecordService personalInsuranceRecordService,
            IDictionaryReferenceService dictionaryService,
            IAgentAreaRecordData agentAreaRecordData)
        {
            this.driverData = driverData;
            this.provinceData = provinceData;
            this.cityData = cityData;
            this.countyData = countyData;
            this.userData = userData;
            this.databaseContext = databaseContext;
            this.ipAddressRecordData = ipAddressRecordData;
            this.redisService = redisService;
            this.agentRecordData = agentRecordData;
            this.pendingLearningTrainData = pendingLearningTrainData;
            this.workingCompanyData = workingCompanyData;
            this.agentRecordService = agentRecordService;
            this.vehicleTypeService = vehicleTypeService;
            this.fenceService = fenceService;
            this.personalInsuranceRecordService = personalInsuranceRecordService;
            this.dictionaryService = dictionaryService;
            this.agentAreaRecordData = agentAreaRecordData;
        }

        #region 新增

        public DriverDto Add(AdminDto admin, DriverRequestDto driverRequestDto, string ip)
        {
            if (admin.AgentRecord == null)
            {
                throw new ArgumentException("没有权限操作，需要联系总部");
            }
            if (this.driverData.CheckDriverExistsByPhoneAsync(driverRequestDto.Phone).GetAwaiter().GetResult())
            {
                throw new ArgumentException("手机号已存在。");
            }
            if (this.driverData.CheckDriverExistsByVehicleNoAsync(driverRequestDto.VehicleNo).GetAwaiter().GetResult())
            {
                throw new ArgumentException($"此{driverRequestDto.VehicleNo}车牌号已存在。");
            }
            if (driverRequestDto.VehicleTypeId <= 0)
            {
                throw new ArgumentException("请选择车型!");
            }
            var vehicleType = this.vehicleTypeService.GetById(driverRequestDto.VehicleTypeId);
            if (vehicleType == null)
            {
                throw new ArgumentException("车型信息不存在");
            }
            //校验省市区
            var province = this.provinceData.GetProvince(driverRequestDto.ProvinceCode);
            if (province == null)
                throw new ArgumentException("注册省份信息不存在");
            var city = this.cityData.GetCity(driverRequestDto.CityCode);
            if (city == null)
                throw new ArgumentException("注册城市信息不存在");
            var county = this.countyData.GetCounty(driverRequestDto.CountyCode);
            if (county == null)
                throw new ArgumentException("注册区/县信息不存在");

            var agentAreaRecord = this.agentAreaRecordData.GetByAgentRecordIdAndCountyCode(admin.AgentRecord.AgentRecordId, driverRequestDto.CountyCode).Result;
            if (agentAreaRecord == null)
            {
                throw new ArgumentException(" 当前行政区域没有权限新增司机 ");
            }

            if (driverRequestDto.IsTrained.HasValue && driverRequestDto.IsTrained.Value)
            {
                if (!driverRequestDto.IsTrainPassed.HasValue)
                    throw new ArgumentException("请选择培训是否通过!");
                if (!driverRequestDto.TrainPassedTime.HasValue)
                    throw new ArgumentException("请选择培训通过时间!");
            }


            DriverEntity entity = driverRequestDto.As<DriverEntity>();
            if (string.IsNullOrWhiteSpace(driverRequestDto.DriverPhotoPath))
            {
                entity.DriverPhotoPath = GeneralContainer.Configuration["CurrentlyImageHost"] + "/assets/image/default_avatar.png";
            }
            if (!String.IsNullOrWhiteSpace(driverRequestDto.Password))
            {
                entity.Password = driverRequestDto.Password.SHA256(driverRequestDto.Phone);
            }
            entity.Role = DriverRoleType.Driver.ToString();
            entity.Source = DriverSourceType.System;
            entity.VehicleType = vehicleType.VehicleTypeName;
            entity.ProvinceId = province.ProvinceId;
            entity.ProvinceCode = province.ProvinceCode;
            entity.ProvinceName = province.ProvinceName;
            entity.CityId = city.CityId;
            entity.CityCode = city.CityCode;
            entity.CityName = city.CityName;
            entity.CountyId = county.CountyId;
            entity.CountyCode = county.CountyCode;
            entity.CountyName = county.CountyName;
            entity.RealNameVerifiesStatus = RealNameVerifiesStatus.Pending.ToString();

            #region 代理商信息
            if (admin.AgentRecord != null)
            {
                entity.AgentRecordId = admin.AgentRecord.AgentRecordId;
                var agentRecordDto = this.agentRecordService.Get(admin.AgentRecord.AgentRecordId);
                entity.AgentRecordId = agentRecordDto.AgentRecordId;
                entity.AgentRecordUuid = agentRecordDto.AgentRecordUuid;
                entity.CompanyId = agentRecordDto.CompanyId;
            }
            #endregion

            IPAddressRecordEntity iPAddressRecordEntity = new IPAddressRecordDto() { StartIP = ip }.As<IPAddressRecordEntity>();
            IPAddressRecordEntity iPAddressRecordEntityResult = ipAddressRecordData.Get(iPAddressRecordEntity);
            string addressIp = iPAddressRecordEntityResult != null ? iPAddressRecordEntityResult.IANA : "未知IP地址";

            var pendingLearningTrain = new PendingLearningVehicleEntity()
            {
                CompanyId = entity.CompanyId,
                IsNotifyPayment = false,
                NotifyTime = null,
                IsAbsenteeism = false,
                VehicleTrainingScheduleRecordId = null,
                CreateTime = DateTime.Now,
            };
            this.databaseContext.BeginTransaction();
            var result = this.driverData.InsertAsync(entity, "000000", ip, addressIp).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("创建司机账号失败,请重试!");
            }
            pendingLearningTrain.DriverId = result.DriverId;
            this.pendingLearningTrainData.InsertAsync(pendingLearningTrain).GetAwaiter().GetResult();
            this.databaseContext.Commit();
            this.redisService.DeleteMultipleKey(keyPendingLearningVehicle, false);
            this.redisService.DeleteMultipleKey(key, false);
            this.redisService.DeleteMultipleKey(userKey, false);
            return result.As<DriverDto>();
        }


        public DriverDto AddHorseman(AdminDto admin, HorsemanRequestDto horsemanRequestDto, string ip)
        {
            if (admin.AgentRecord == null)
            {
                throw new ArgumentException("没有权限操作，需要联系总部");
            }
            if (this.driverData.CheckDriverExistsByPhoneAsync(horsemanRequestDto.Phone).GetAwaiter().GetResult())
            {
                throw new ArgumentException("手机号已存在。");
            }
            if (this.driverData.CheckDriverExistsByVehicleNoAsync(horsemanRequestDto.VehicleNo).GetAwaiter().GetResult())
            {
                throw new ArgumentException($"此{horsemanRequestDto.VehicleNo}车牌号已存在。");
            }
            if (horsemanRequestDto.VehicleTypeId <= 0)
            {
                throw new ArgumentException("请选择车型!");
            }
            var vehicleType = this.vehicleTypeService.GetById(horsemanRequestDto.VehicleTypeId);
            if (vehicleType == null)
            {
                throw new ArgumentException("车型信息不存在");
            }

            #region 摩托车
            var dictionary = dictionaryService.GetBySearchkeyAsync(vehicleType.VehicleTypeEnum).Result;
            if (dictionary.Any(s => s.SearchKey == "VehicleTypeEnum_Motorcycle_MaterialConfiguration"))
            {
                if (string.IsNullOrEmpty(horsemanRequestDto.VehicleLicense))
                {
                    throw new ArgumentException("行驶证正面图片不能为空");
                }
                if (string.IsNullOrEmpty(horsemanRequestDto.VehicleLicenseDeputyPage))
                {
                    throw new ArgumentException("行驶证车照图片不能为空");
                }
                if (string.IsNullOrEmpty(horsemanRequestDto.License))
                {
                    throw new ArgumentException("驾驶证车正面不能为空");
                }
                if (string.IsNullOrEmpty(horsemanRequestDto.LicenseDeputyPage))
                {
                    throw new ArgumentException("驾驶证副页不能为空");
                }
                if (string.IsNullOrEmpty(horsemanRequestDto.VehiclePhotoFrontPath))
                {
                    throw new ArgumentException("车辆前方照不能为空");
                }
                if (string.IsNullOrEmpty(horsemanRequestDto.VehiclePhotoBackPath))
                {
                    throw new ArgumentException("车辆后方照片不能为空");
                }
            }
            #endregion

            //校验骑手非空信息
            if (horsemanRequestDto.DeliveryBoxLength <= 0)
            {
                throw new ArgumentException("配送箱长不能为空");
            }
            if (horsemanRequestDto.DeliveryBoxWidth <= 0)
            {
                throw new ArgumentException("配送箱宽不能为空");
            }
            if (horsemanRequestDto.DeliveryBoxHeight <= 0)
            {
                throw new ArgumentException("配送箱高不能为空");
            }
            //校验省市区           
            var county = this.countyData.GetCounty(horsemanRequestDto.CountyCode);
            if (county == null)
                throw new ArgumentException("注册区/县信息不存在");
            var agentAreaRecord = this.agentAreaRecordData.GetByAgentRecordIdAndCountyCode(admin.AgentRecord.AgentRecordId, horsemanRequestDto.CountyCode).Result;
            if (agentAreaRecord == null)
            {
                throw new ArgumentException(" 当前行政区域没有权限新增骑手 ");
            }
            if (horsemanRequestDto.WorkCompanyId <= 0)
            {
                throw new ArgumentException("劳务公司信息不能为空");
            }
            var workingCompany = this.workingCompanyData.GetEntity(horsemanRequestDto.WorkCompanyId).GetAwaiter().GetResult();
            if (workingCompany == null)
            {
                throw new ArgumentException("劳务公司信息不存在");
            }
            #region 电子围栏信息
            var fence = this.fenceService.GetByWorkCompanyIdAndCountyCode(workingCompany.WorkingCompanyId, county.CountyCode);
            if (fence == null)
            {
                throw new ArgumentException($"该 {workingCompany.WorkingCompanyName} 劳务公司未给骑手设置电子围栏信息，操作失败");
            }
            #endregion

            if (horsemanRequestDto.IsTrained.HasValue && horsemanRequestDto.IsTrained.Value)
            {
                if (!horsemanRequestDto.IsTrainPassed.HasValue)
                    throw new ArgumentException("请选择培训是否通过!");
                if (!horsemanRequestDto.TrainPassedTime.HasValue)
                    throw new ArgumentException("请选择培训通过时间!");
            }
            DriverEntity entity = horsemanRequestDto.As<DriverEntity>();

            #region 代理商信息

            var agentRecordDto = this.agentRecordService.Get(admin.AgentRecord.AgentRecordId);
            entity.AgentRecordId = agentRecordDto.AgentRecordId;
            entity.CompanyId = agentRecordDto.CompanyId;
            entity.AgentRecordUuid = agentRecordDto.AgentRecordUuid;
            #endregion

            #region 个人保单信息
            if (horsemanRequestDto.PersonalInsuranceRecordId > 0)
            {
                var personalInsuranceRecord = this.personalInsuranceRecordService.GetByPersonalInsuranceRecordId(horsemanRequestDto.PersonalInsuranceRecordId);
                if (personalInsuranceRecord == null)
                {
                    throw new ArgumentException("个人保单信息不存在，或保单已经失效。");
                }
            }
            #endregion
            if (!String.IsNullOrWhiteSpace(horsemanRequestDto.Password))
            {
                entity.Password = horsemanRequestDto.Password.SHA256(horsemanRequestDto.Phone);
            }
            if (string.IsNullOrWhiteSpace(horsemanRequestDto.DriverPhotoPath))
            {
                entity.DriverPhotoPath = GeneralContainer.Configuration["CurrentlyImageHost"] + "/assets/image/default_avatar.png";
            }
            entity.Role = DriverRoleType.Horseman.ToString();
            entity.Source = DriverSourceType.System;
            entity.ProvinceId = county.ProvinceId;
            entity.ProvinceCode = county.ProvinceCode;
            entity.ProvinceName = county.ProvinceName;
            entity.CityId = county.CityId;
            entity.CityCode = county.CityCode;
            entity.CityName = county.CityName;
            entity.CountyId = county.CountyId;
            entity.CountyCode = county.CountyCode;
            entity.CountyName = county.CountyName;
            entity.WorkingCompanyId = workingCompany.WorkingCompanyId;
            entity.WorkingCompanyName = workingCompany.WorkingCompanyName;
            entity.RealNameVerifiesStatus = RealNameVerifiesStatus.Pending.ToString();

            #region IP信息
            IPAddressRecordEntity iPAddressRecordEntity = new IPAddressRecordDto() { StartIP = ip }.As<IPAddressRecordEntity>();
            IPAddressRecordEntity iPAddressRecordEntityResult = ipAddressRecordData.Get(iPAddressRecordEntity);
            string addressIp = iPAddressRecordEntityResult != null ? iPAddressRecordEntityResult.IANA : "未知IP地址";

            #endregion

            #region 待培训信息
            var pendingLearningTrain = new PendingLearningVehicleEntity()
            {
                CompanyId = entity.CompanyId,
                IsNotifyPayment = false,
                NotifyTime = null,
                IsAbsenteeism = false,
                VehicleTrainingScheduleRecordId = null,
                CreateTime = DateTime.Now,
            };

            #endregion

            this.databaseContext.BeginTransaction();
            var result = this.driverData.InsertAsync(entity, "000000", ip, addressIp).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("创建骑手账号失败,请重试!");
            }
            pendingLearningTrain.DriverId = result.DriverId;
            this.pendingLearningTrainData.InsertAsync(pendingLearningTrain).GetAwaiter().GetResult();
            this.databaseContext.Commit();
            this.redisService.DeleteMultipleKey(keyPendingLearningVehicle, false);
            this.redisService.DeleteMultipleKey(key, false);
            this.redisService.DeleteMultipleKey(userKey, false);
            return result.As<DriverDto>();
        }

        /// <summary>
        /// 用手机号和密码注册司机
        /// </summary>
        /// <param name="userRequestDto"></param> 
        /// <param name="ip"></param>
        /// <param name="driverSource">司机来源</param>
        /// <returns></returns>
        public UserDto Register(UserRequestDto userRequestDto, string ip, DriverSourceType driverSource)
        {
            var driver = this.driverData.GetDriverByPhoneAsync(userRequestDto.Phone).GetAwaiter().GetResult();
            if (driver != null)
            {
                throw new ArgumentException("手机号已被注册。");
            }

            DriverEntity entity = new DriverEntity
            {
                Phone = userRequestDto.Phone,
                Password = userRequestDto.Password.SHA256(userRequestDto.Phone),
                Source = driverSource,
                DriverPhotoPath = GeneralContainer.Configuration["CurrentlyImageHost"] + "/assets/image/default_avatar.png",
                Name = userRequestDto.UserName
            };
#if DEBUG
            entity.Password = userRequestDto.Password.SHA256(userRequestDto.Phone.TrimStart('0'));

#else
            string pwd = AESUtils.AESDecrypt(userRequestDto.Password);
            entity.Password = pwd.SHA256(userRequestDto.Phone.TrimStart('0'));
#endif

            #region 邀请信息
            if (!string.IsNullOrWhiteSpace(userRequestDto.UniqueCode))
            {
                var user = this.userData.GetUserByUniqueCode(userRequestDto.UniqueCode).GetAwaiter().GetResult();
                if (user == null)
                {
                    throw new ArgumentException("邀请码有误。");
                }
                //更新父级Id
                this.userData.UpdateUserParent(driver.UserId, user.UserId).GetAwaiter().GetResult();
            }
            #endregion

            IPAddressRecordEntity iPAddressRecordEntity = new IPAddressRecordDto() { StartIP = ip }.As<IPAddressRecordEntity>();
            IPAddressRecordEntity iPAddressRecordEntityResult = ipAddressRecordData.Get(iPAddressRecordEntity);
            string addressIp = iPAddressRecordEntityResult != null ? iPAddressRecordEntityResult.IANA : "未知IP地址";
            this.databaseContext.BeginTransaction();
            var result = this.driverData.InsertAsync(entity, userRequestDto.PassCode, ip, addressIp).GetAwaiter().GetResult();
            if (result == null)
            {
                this.databaseContext.Rollback();
                throw new ArgumentException("注册失败,请重试。");
            }
            this.databaseContext.Commit();
            this.redisService.DeleteMultipleKey(key, false);
            this.redisService.DeleteMultipleKey(userKey, false);
            return userData.GetUserByPhone(userRequestDto.Phone).GetAwaiter().GetResult().As<UserDto>();
        }
        #endregion

        #region 查询
        /// <summary>
        /// 获取司机信息列表（分页）
        /// </summary>
        /// <param name="companyId">总公司/代理商Id</param>
        /// <param name="phone">手机</param>
        /// <param name="name">司机名</param>
        /// <param name="vehicleNo">车牌号</param>
        /// <param name="provinceCode">省编码</param>
        /// <param name="cityCode">市编码</param>
        /// <param name="countyCode">区县编码</param>
        /// <param name="driverStatus">审核状态</param>       
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>       
        /// <param name="role">司机角色</param>       
        /// <param name="ascending">是否升序排序</param>
        /// <param name="sortName">排序字段</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页条数</param>
        public PageableList<DriverDto> GetList(long? companyId, string phone, string name, string vehicleNo, string provinceCode, string cityCode, string countyCode, DriverStatus? driverStatus, DriverRoleType? role, DateTime? start, DateTime? end, bool? ascending, string sortName, int pageIndex, int pageSize)
        {
            var queryResult = this.driverData.GetDriversAsync(companyId, phone, name, vehicleNo, provinceCode, cityCode, countyCode, driverStatus, role, start, end, ascending, sortName, pageIndex, pageSize).GetAwaiter().GetResult();
            var drivers = queryResult.Item1.As<IEnumerable<DriverDto>>();

            foreach (DriverDto item in drivers)
            {
                if (item.ElectricFenceId.HasValue)
                {
                    item.Fence = this.fenceService.GetById(item.ElectricFenceId.Value);
                }

                if (item.AgentRecordId.HasValue)
                {
                    item.AgentRecord = agentRecordService.GetViewByAgentRecordId(item.AgentRecordId.Value);
                }
            }
            return new PageableList<DriverDto>
            {
                Count = queryResult.Item2,
                Items = drivers,
                ServerTime = DateTime.Now,
                PageIndex = pageIndex,
                PageSize = pageSize
            };
        }


        /// <summary>
        /// 根据手机号查询司机信息
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <returns></returns>
        public DriverDto GetDriverByPhone(string phone)
        {
            if (string.IsNullOrWhiteSpace(phone))
            {
                throw new ArgumentException("手机号不能为空。");
            }
            string cacheKey = this.redisService.GetKey(key, phone);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.driverData.GetDriverByPhoneAsync(phone).GetAwaiter().GetResult();
                if (data == null)
                {
                    throw new ArgumentException("司机信息不存在。");
                }
                if (data.AgentRecordId.HasValue)
                {
                    var agentRecord = this.agentRecordService.GetViewByAgentRecordId(data.AgentRecordId.Value);
                }
                return data.As<DriverDto>();
            }, TimeSpan.FromDays(30));
            return result;
        }


        /// <summary>
        /// 根据司机Id查询司机信息
        /// </summary>
        /// <param name="driverId">司机Id</param>
        /// <returns></returns>
        public DriverDto GetDriverById(long driverId)
        {
            if (driverId <= 0)
            {
                throw new ArgumentException("司机Id不能为空。");
            }
            string cacheKey = this.redisService.GetKey(key, driverId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.driverData.GetDriverByIdAsync(driverId).GetAwaiter().GetResult().As<DriverDto>();
                if (data == null)
                {
                    throw new ArgumentException("司机信息不存在。");
                }
                if (data.ElectricFenceId.HasValue)
                {
                    data.Fence = this.fenceService.GetById(data.ElectricFenceId.Value);
                }
                if (data.AgentRecordId.HasValue)
                {
                    data.AgentRecord = agentRecordService.GetViewByAgentRecordId(data.AgentRecordId.Value);
                }
                return data;
            }, TimeSpan.FromDays(30));
            return result;
        }
        /// <summary>
        /// 根据登录名和密码查询司机信息
        /// </summary>
        /// <param name="phone">登录名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public DriverDto GetDriverByPhoneAndPassword(string phone, string password)
        {
            string cacheKey = this.redisService.GetKey(key, phone, password);
            if (string.IsNullOrWhiteSpace(phone))
            {
                throw new ArgumentException("手机号不能为空。");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("密码不能为空。");
            }
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.driverData.GetDriverByPhoneAndPasswordAsync(phone, password.SHA256(phone)).GetAwaiter().GetResult();
                if (data == null)
                {
                    throw new ArgumentException("手机号或密码不正确。");
                }
                return data.As<DriverDto>();
            }, TimeSpan.FromDays(30));
            return result;
        }



        public DriverDto GetDriverByUserId(long userId)
        {
            string cacheKey = this.redisService.GetKey(key, userId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.driverData.GetDriverByUserIdAsync(userId).GetAwaiter().GetResult().As<DriverDto>();

                if (data == null)
                {
                    throw new ArgumentException("司机信息不存在。");
                }
                return data.As<DriverDto>();
            }, TimeSpan.FromDays(30));
            return result;
        }
        public DriverDto GetDriverByVehicleNo(string vehicleNo)
        {
            string cacheKey = this.redisService.GetKey(key, vehicleNo);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.driverData.GetDriverByVehicleNoAsync(vehicleNo).GetAwaiter().GetResult().As<DriverDto>();

                if (data == null)
                {
                    throw new ArgumentException("车辆信息不存在。");
                }
                return data.As<DriverDto>();
            }, TimeSpan.FromDays(30));
            return result;
        }



        public IEnumerable<DriverDto> GetALLApprovedList(long? companyId)
        {
            string cacheKey = this.redisService.GetKey(key, companyId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.driverData.GetALLApprovedDriversAsync(companyId).GetAwaiter().GetResult();
                return data.As<IEnumerable<DriverDto>>();
            }, TimeSpan.FromDays(30));
            return result;
        }
        #endregion

        #region 认证

        /// <summary>
        /// 实名认证
        /// </summary>
        /// <param name="driverId">当前实名司机Id</param>
        /// <param name="dto">司机实名信息</param>
        /// <returns></returns>
        public DriverDto RealNameVerifies(long driverId, RealNameVerifiesRequestDto dto)
        {
            var driver = this.driverData.GetDriverByIdAsync(driverId).GetAwaiter().GetResult();
            if (driver == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }
            var driverEntity = new DriverEntity()
            {
                DriverId = driverId,
                RealName = dto.RealName,
                IdentityCardNo = dto.IdentityCardNo,
                IdentityCardPath = dto.IdentityCardPath,
                IdentityCardBackPath = dto.IdentityCardBackPath,
                IsRealNameVerified = false,
                RealNameVerifiesStatus = RealNameVerifiesStatus.Pending.ToString()
            };
            var userEntity = new UserEntity()
            {
                UserId = driver.UserId,
                RealName = dto.RealName,
                IdentityCardNo = dto.IdentityCardNo,
                IdentityCardPath = dto.IdentityCardPath,
                IdentityCardBackPath = dto.IdentityCardBackPath,
                RealNameVerifiesStatus = RealNameVerifiesStatus.Pending.ToString()
            };
            this.databaseContext.BeginTransaction();
            var user = this.userData.RealNameVerifiesAsync(userEntity).GetAwaiter().GetResult();
            if (user == null)
            {
                this.databaseContext.Rollback();
                throw new ArgumentException("司机实名认证失败。");
            }
            var result = this.driverData.RealNameVerifiesAsync(driverEntity).GetAwaiter().GetResult();
            if (result == null)
            {
                this.databaseContext.Rollback();
                throw new ArgumentException("司机实名认证失败。");
            }
            string userCacheKey = string.Format("{0}:UserId={1}", EntityNameConst.UserEntity, driver.UserId);
            this.redisService.DeleteMultipleKey(userCacheKey, false);
            string cacheKey = this.redisService.GetKey(key, driverId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<DriverDto>();
        }

        /// <summary>
        /// 人脸识别认证
        /// </summary>
        /// <param name="driverId">当前人脸识别司机Id</param>
        /// <param name="dto">人脸识别信息</param>
        /// <returns></returns>
        public DriverDto FaceVerifies(long driverId, FaceVerifiesRequestDto dto)
        {
            if (this.driverData.GetDriverByIdAsync(driverId).GetAwaiter().GetResult() == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }
            var driver = new DriverEntity()
            {
                DriverId = driverId,
                FacePic = dto.FacePic
            };
            var result = this.driverData.FaceVerifiesAsync(driver).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("司机人脸识别认证失败。");
            }
            string cacheKey = this.redisService.GetKey(key, driverId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<DriverDto>();
        }


        #endregion

        #region 工作城市
        /// <summary>
        /// 切换城市信息
        /// </summary>
        /// <param name="driverId">司机Id</param>
        /// <param name="dto">城市信息</param>
        /// <returns></returns>
        public DriverDto ChangeCity(long driverId, ChangeCityRequestDto dto)
        {
            if (this.driverData.GetDriverByIdAsync(driverId).GetAwaiter().GetResult() == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }
            //校验省市区
            var province = this.provinceData.GetProvince(dto.ProvinceCode);
            if (province == null)
                throw new ArgumentException("注册省份信息不存在");
            var city = this.cityData.GetCity(dto.CityCode);
            if (city == null)
                throw new ArgumentException("注册城市信息不存在");
            var county = this.countyData.GetCounty(dto.CountyCode);
            if (county == null)
                throw new ArgumentException("注册区/县信息不存在");
            var entity = new DriverEntity
            {
                DriverId = driverId,
                ProvinceId = province.ProvinceId,
                ProvinceCode = province.ProvinceCode,
                ProvinceName = province.ProvinceName,
                CityId = city.CityId,
                CityCode = city.CityCode,
                CityName = city.CityName,
                CountyId = county.CountyId,
                CountyCode = county.CountyCode,
                CountyName = county.CountyName
            };
            var result = this.driverData.ChangeCityAsync(entity).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("司机上传车辆信息失败。");
            }
            string cacheKey = this.redisService.GetKey(key, driverId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<DriverDto>();
        }

        #endregion

        #region 工作状态
        public DriverDto ChangeWorkingStatus(long driverId, DriverWorkingStatusForApp workingStatus)
        {
            if (this.driverData.GetDriverByIdAsync(driverId).GetAwaiter().GetResult() == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }
            var entity = new DriverEntity
            {
                DriverId = driverId,
                WorkingStatus = (DriverWorkingStatus)workingStatus
            };
            var result = this.driverData.ChangeWorkingStatusAsync(entity).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("司机切换工作状态失败。");
            }
            string cacheKey = this.redisService.GetKey(key, driverId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<DriverDto>();
        }
        #endregion

        #region 审核

        /// <summary>
        /// 实名认证审核
        /// </summary>
        /// <param name="admin">审核人员</param>
        /// <param name="driverId">司机信息</param>
        /// <param name="dto">审核信息</param>
        /// <returns></returns>
        public DriverDto RealNameVerifiesApprove(AdminDto admin, long driverId, ApproveRequestDto dto)
        {
            if (admin.AgentRecord == null)
            {
                throw new ArgumentException("没有审核权限，需要联系总公司");
            }
            var driver = this.driverData.GetDriverByIdAsync(driverId).GetAwaiter().GetResult();
            if (driver == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }
            if (admin.AgentRecord.AgentRecordId != driver.AgentRecordId)
            {
                throw new ArgumentException("该司机不属于您管辖范围，不能审核");
            }
            if (!dto.IsApproved)
            {
                if (string.IsNullOrWhiteSpace(dto.RefuseToReason))
                {
                    throw new ArgumentException("审核不通过,请填写原因。");
                }
            }
            var entity = new DriverEntity
            {
                DriverId = driverId,
                IsRealNameVerified = dto.IsApproved,
                RealNameVerifiesRefuse = dto.RefuseToReason,
                RealNameVerifiesStatus = dto.IsApproved ? RealNameVerifiesStatus.Success.ToString() : RealNameVerifiesStatus.Refused.ToString(),
                Approver = admin.FullName,
                ApproverId = admin.AdminId,
                ApproveTime = DateTime.Now
            };
            var userEntity = new UserEntity()
            {
                UserId = driver.UserId,
                RealNameVerifiesRefuse = dto.RefuseToReason,
                RealNameVerifiesStatus = dto.IsApproved ? RealNameVerifiesStatus.Success.ToString() : RealNameVerifiesStatus.Refused.ToString(),
                Approver = admin.FullName,
                ApproverId = admin.AdminId,
                ApproveTime = DateTime.Now
            };
            this.databaseContext.BeginTransaction();
            var user = this.userData.RealNameVerifiesApproveAsync(userEntity).GetAwaiter().GetResult();
            if (user == null)
            {
                throw new ArgumentException("实名认证审核失败。");
            }
            var result = this.driverData.RealNameVerifiesApproveAsync(entity).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("实名认证审核失败。");
            }
            this.databaseContext.Commit();
            string userCacheKey = string.Format("{0}:UserId={1}", EntityNameConst.UserEntity, driver.UserId);
            this.redisService.DeleteMultipleKey(userCacheKey, false);
            string cacheKey = this.redisService.GetKey(key, driverId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<DriverDto>();
        }

        /// <summary>
        /// 人脸识别认证审核
        /// </summary>
        /// <param name="admin">审核人员</param>
        /// <param name="driverId">司机信息</param>
        /// <param name="dto">审核信息</param>
        /// <returns></returns>

        public DriverDto FaceVerifiesApprove(AdminDto admin, long driverId, ApproveRequestDto dto)
        {
            if (admin.AgentRecord == null)
            {
                throw new ArgumentException("没有审核权限，需要联系总公司");
            }
            var driver = this.driverData.GetDriverByIdAsync(driverId).GetAwaiter().GetResult();
            if (driver == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }
            if (admin.AgentRecord.AgentRecordId != driver.AgentRecordId)
            {
                throw new ArgumentException("该司机不属于您管辖范围，不能审核");
            }
            if (!dto.IsApproved)
            {
                if (string.IsNullOrWhiteSpace(dto.RefuseToReason))
                {
                    throw new ArgumentException("审核不通过,请填写原因。");
                }
            }
            var entity = new DriverEntity
            {
                DriverId = driverId,
                IsRealNameVerified = dto.IsApproved,
                RealNameVerifiesRefuse = dto.RefuseToReason
            };
            var result = this.driverData.FaceVerifiesApproveAsync(entity).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("人脸识别认证审核失败。");
            }
            string cacheKey = this.redisService.GetKey(key, driverId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<DriverDto>();
        }

        /// <summary>
        /// 车辆审核
        /// </summary>
        /// <param name="admin">审核人员</param>
        /// <param name="driverId">当前司机Id</param>
        /// <param name="dto">审核信息</param>
        /// <returns></returns>
        public DriverDto VehicleApprove(AdminDto admin, long driverId, ApproveRequestDto dto)
        {
            if (admin.AgentRecord == null)
            {
                throw new ArgumentException("没有审核权限，需要联系总公司");
            }
            var driver = this.driverData.GetDriverByIdAsync(driverId).GetAwaiter().GetResult();
            if (driver == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }
            if (admin.AgentRecord.AgentRecordId != driver.AgentRecordId)
            {
                throw new ArgumentException("该司机不属于您管辖范围，不能审核");
            }
            if (!dto.IsApproved)
            {
                if (string.IsNullOrWhiteSpace(dto.RefuseToReason))
                {
                    throw new ArgumentException("审核不通过,请填写原因。");
                }
            }
            var entity = new DriverEntity
            {
                DriverId = driverId,
                DriverStatus = dto.IsApproved ? DriverStatus.Success : DriverStatus.Refused,
                RefuseToReason = dto.RefuseToReason,
                Approver = admin.FullName,
                ApproverId = admin.AdminId,
                ApproveTime = DateTime.Now
            };
            var result = this.driverData.VehicleApproveAsync(entity).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("车辆审核失败。");
            }
            string cacheKey = this.redisService.GetKey(key, driverId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<DriverDto>();
        }

        #endregion

        #region 上传信息

        /// <summary>
        /// 上传机动车辆信息
        /// </summary>
        /// <param name="driverId">司机Id</param>
        /// <param name="dto">机动车信息</param>
        /// <returns></returns>
        public DriverDto UploadVehicle(long driverId, VehicleRequestDto dto)
        {
            var currentDriver = this.driverData.GetDriverByIdAsync(driverId).GetAwaiter().GetResult();
            if (currentDriver == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }
            if (dto.VehicleTypeId <= 0)
            {
                throw new ArgumentException("请选择车型!");
            }
            var vehicleType = this.vehicleTypeService.GetById(dto.VehicleTypeId);
            if (vehicleType == null)
            {
                throw new ArgumentException("车型信息不存在");
            }
            //校验省市区
            var province = this.provinceData.GetProvince(dto.ProvinceCode);
            if (province == null)
                throw new ArgumentException("注册省份信息不存在");
            var city = this.cityData.GetCity(dto.CityCode);
            if (city == null)
                throw new ArgumentException("注册城市信息不存在");
            var county = this.countyData.GetCounty(dto.CountyCode);
            if (county == null)
                throw new ArgumentException("注册区/县信息不存在");
            var entity = dto.As<DriverEntity>();
            entity.DriverId = driverId;
            entity.UserId = currentDriver.UserId;
            entity.Role = RoleType.Driver.ToString();
            entity.ProvinceId = province.ProvinceId;
            entity.ProvinceCode = province.ProvinceCode;
            entity.ProvinceName = province.ProvinceName;
            entity.CityId = city.CityId;
            entity.CityCode = city.CityCode;
            entity.CityName = city.CityName;
            entity.CountyId = county.CountyId;
            entity.CountyCode = county.CountyCode;
            entity.CountyName = county.CountyName;
            entity.DriverStatus = DriverStatus.Pending;

            #region 获取代理商信息
            this.GetAgentRecord(currentDriver, dto.AgentUuid, ref entity, county);
            #endregion

            this.databaseContext.BeginTransaction();
            var result = this.driverData.UpdateVehicleAsync(entity).GetAwaiter().GetResult();
            if (result == null)
            {
                this.databaseContext.Rollback();
                throw new ArgumentException("司机上传车辆信息失败。");
            }
            this.databaseContext.Commit();
            string cacheKey = this.redisService.GetKey(key, driverId);
            string userCacheKey = this.redisService.GetKey(userKey, result.UserId);
            this.redisService.DeleteMultipleKey(userCacheKey, false);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<DriverDto>();
        }

        /// <summary>
        /// 上传电动车辆信息
        /// </summary>
        /// <param name="driverId">司机Id</param>
        /// <param name="dto">电动车辆信息</param>
        /// <returns></returns>
        public DriverDto UploadElectricVehicle(long driverId, ElectricVehicleRequestDto dto)
        {
            var currentDriver = this.driverData.GetDriverByIdAsync(driverId).GetAwaiter().GetResult();
            if (currentDriver == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }
            if (dto.VehicleTypeId <= 0)
            {
                throw new ArgumentException("请选择车型!");
            }
            var vehicleType = this.vehicleTypeService.GetById(dto.VehicleTypeId);
            if (vehicleType == null)
            {
                throw new ArgumentException("车型信息不存在");
            }
            if (dto.DeliveryBoxLength <= 0)
            {
                throw new ArgumentException("配送箱长不能为空");
            }
            if (dto.DeliveryBoxWidth <= 0)
            {
                throw new ArgumentException("配送箱宽不能为空");
            }
            if (dto.DeliveryBoxHeight <= 0)
            {
                throw new ArgumentException("配送箱高不能为空");
            }
            var province = this.provinceData.GetProvince(dto.ProvinceCode);
            if (province == null)
                throw new ArgumentException("注册省份信息不存在");
            var city = this.cityData.GetCity(dto.CityCode);
            if (city == null)
                throw new ArgumentException("注册城市信息不存在");
            var county = this.countyData.GetCounty(dto.CountyCode);
            if (county == null)
                throw new ArgumentException("注册区/县信息不存在");
            if (dto.WorkCompanyId <= 0)
            {
                throw new ArgumentException("劳务公司信息不能为空");
            }
            var workingCompany = this.workingCompanyData.GetEntity(dto.WorkCompanyId).GetAwaiter().GetResult();
            if (workingCompany == null)
            {
                throw new ArgumentException("劳务公司信息不存在");
            }

            #region 电子围栏信息
            var fence = this.fenceService.GetByWorkCompanyIdAndCountyCode(workingCompany.WorkingCompanyId, county.CountyCode);
            if (fence == null)
            {
                throw new ArgumentException($"该 {workingCompany.WorkingCompanyName} 劳务公司未给骑手设置电子围栏信息，操作失败");
            }
            #endregion

            #region 摩托车
            var dictionary = dictionaryService.GetBySearchkeyAsync(vehicleType.VehicleTypeEnum).Result;
            if (dictionary.Any(s => s.SearchKey == "VehicleTypeEnum_Motorcycle_MaterialConfiguration"))
            {
                if (string.IsNullOrEmpty(dto.VehicleLicense))
                {
                    throw new ArgumentException("行驶证正面图片不能为空");
                }
                if (string.IsNullOrEmpty(dto.VehicleLicenseDeputyPage))
                {
                    throw new ArgumentException("行驶证车照图片不能为空");
                }
                if (string.IsNullOrEmpty(dto.DriverLicense))
                {
                    throw new ArgumentException("驾驶证车正面不能为空");
                }
                if (string.IsNullOrEmpty(dto.DriverLicenseDeputyPage))
                {
                    throw new ArgumentException("驾驶证副页不能为空");
                }
                if (string.IsNullOrEmpty(dto.VehiclePhotoFrontPath))
                {
                    throw new ArgumentException("车辆前方照不能为空");
                }
                if (string.IsNullOrEmpty(dto.VehiclePhotoBackPath))
                {
                    throw new ArgumentException("车辆后方照片不能为空");
                }
            }
            #endregion

            var entity = dto.As<DriverEntity>();
            entity.DriverId = driverId;
            entity.UserId = currentDriver.UserId;
            entity.Role = DriverRoleType.Horseman.ToString();
            entity.ProvinceId = province.ProvinceId;
            entity.ProvinceCode = province.ProvinceCode;
            entity.ProvinceName = province.ProvinceName;
            entity.CityId = city.CityId;
            entity.CityCode = city.CityCode;
            entity.CityName = city.CityName;
            entity.CountyId = county.CountyId;
            entity.CountyCode = county.CountyCode;
            entity.CountyName = county.CountyName;
            entity.DriverStatus = DriverStatus.Pending;
            entity.WorkingCompanyId = workingCompany.WorkingCompanyId;
            entity.WorkingCompanyName = workingCompany.WorkingCompanyName;
            entity.ElectricFenceId = fence.FenceId;

            #region 获取代理商信息
            this.GetAgentRecord(currentDriver, dto.AgentUuid, ref entity, county);
            #endregion

            this.databaseContext.BeginTransaction();
            var result = this.driverData.UpdateElectricVehicleAsync(entity).GetAwaiter().GetResult();
            if (result == null)
            {
                this.databaseContext.Rollback();
                throw new ArgumentException("司机上传车辆信息失败。");
            }
            this.databaseContext.Commit();
            string cacheKey = this.redisService.GetKey(key, driverId);
            string userCacheKey = this.redisService.GetKey(userKey, result.UserId);
            this.redisService.DeleteMultipleKey(userCacheKey, false);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<DriverDto>();
        }

        /// <summary>
        /// 上传健康证信息
        /// </summary>
        /// <param name="driverId">司机信息</param>
        /// <param name="dto">健康证信息</param>
        /// <returns></returns>
        public DriverDto UploadHealthCertificate(long driverId, HealthCertificateRequestDto dto)
        {
            if (this.driverData.GetDriverByIdAsync(driverId).GetAwaiter().GetResult() == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }
            DriverEntity entity = new DriverEntity
            {
                DriverId = driverId,
                HealthCertificate = dto.HealthCertificate,
                HealthCertificateType = dto.HealthCertificateType
            };
            var result = this.driverData.UpdateHealthCertificateAsync(entity).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("上传健康证信息失败。");
            }
            string cacheKey = this.redisService.GetKey(key, driverId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<DriverDto>();
        }
        #endregion

        #region 修改头像

        public bool UpdateAvatar(string phone, string avatar)
        {
            var driver = this.driverData.GetDriverByPhoneAsync(phone).GetAwaiter().GetResult();
            if (driver == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }

            driver.DriverPhotoPath = avatar;
            this.databaseContext.BeginTransaction();
            var result = this.driverData.UpdateAvatarAsync(driver).GetAwaiter().GetResult();
            if (!result)
            {
                throw new ArgumentException("修改头像失败。");
            }
            this.databaseContext.Commit();
            string cacheKey = this.redisService.GetKey(key, driver.DriverId);
            string userCacheKey = this.redisService.GetKey(userKey, driver.UserId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            this.redisService.DeleteMultipleKey(userCacheKey, false);
            return result;
        }

        #endregion

        #region 修改昵称

        public bool UpdatePetname(string phone, string petname)
        {
            var driver = this.driverData.GetDriverByPhoneAsync(phone).GetAwaiter().GetResult();
            if (driver == null)
            {
                throw new ArgumentException("司机信息不存在。");
            }
            driver.Name = petname;
            this.databaseContext.BeginTransaction();
            var result = this.driverData.UpdatePetnameAsync(driver).GetAwaiter().GetResult();
            if (!result)
            {
                throw new ArgumentException("修改昵称失败。");
            }
            this.databaseContext.Commit();
            string cacheKey = this.redisService.GetKey(key, driver.DriverId);
            string userCacheKey = this.redisService.GetKey(userKey, driver.UserId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            this.redisService.DeleteMultipleKey(userCacheKey, false);
            return result;
        }

        #endregion

        #region 获取代理商信息
        private void GetAgentRecord(DriverEntity currentDriver, string agentUuid, ref DriverEntity entity, CountyEntity county)
        {
            //如果注册的时候扫码了
            if (!string.IsNullOrWhiteSpace(agentUuid))
            {
                var agentRecord = this.agentRecordData.GetByUniqueCodeAsync(agentUuid).GetAwaiter().GetResult();
                if (agentRecord == null)
                {
                    throw new ArgumentException("代理商信息不存在");
                }
                if (!currentDriver.AgentRecordId.HasValue)
                {
                    var agentRecordDto = this.agentRecordData.GetTopAgentByCountyCode(county.CountyCode).GetAwaiter().GetResult();
                    if (agentRecordDto == null)
                    {
                        throw new ArgumentException($"该 {county.CountyCode} 区域暂时未开通接单业务,操作失败");
                    }
                    entity.CompanyId = agentRecordDto.CompanyId;
                    entity.AgentRecordUuid = agentRecordDto.AgentRecordUuid;
                    if (agentRecordDto.AgentLevel == 3)
                    {
                        if (agentRecordDto.ParentCompanyId != 1)
                        {
                            var twoAgentRecordDto = this.agentRecordService.GetByCompanyId(agentRecordDto.ParentCompanyId);
                            if (twoAgentRecordDto != null)
                            {
                                entity.TwoAgentRecordId = twoAgentRecordDto.AgentRecordId;
                                if (twoAgentRecordDto.ParentCompanyId != 1)
                                {
                                    var oneAgentRecordDto = this.agentRecordService.GetByCompanyId(twoAgentRecordDto.ParentCompanyId);
                                    if (oneAgentRecordDto != null)
                                    {
                                        entity.OneAgentRecordId = oneAgentRecordDto.AgentRecordId;
                                    }
                                }
                            }
                        }
                    }
                    else if (agentRecordDto.ParentCompanyId != 1)
                    {
                        var oneAgentRecordDto = this.agentRecordService.GetByCompanyId(agentRecordDto.ParentCompanyId);
                        if (oneAgentRecordDto != null)
                        {
                            entity.OneAgentRecordId = oneAgentRecordDto.AgentRecordId;
                        }
                    }
                }
                else
                {
                    entity.AgentRecordId = currentDriver.AgentRecordId.Value;
                    entity.CompanyId = currentDriver.CompanyId;
                }
            }
            //根据司机上传的区县获取代理商
            else
            {
                var agentRecordDto = this.agentRecordData.GetTopAgentByCountyCode(county.CountyCode).GetAwaiter().GetResult();
                if (agentRecordDto == null)
                {
                    throw new ArgumentException($"该 {county.CountyCode} 区域暂时未开通接单业务,上传车辆信息失败");
                }
                entity.CompanyId = agentRecordDto.CompanyId;
                entity.AgentRecordUuid = agentRecordDto.AgentRecordUuid;
                if (agentRecordDto.AgentLevel == 3)
                {
                    if (agentRecordDto.ParentCompanyId != 1)
                    {
                        var twoAgentRecordDto = this.agentRecordService.GetByCompanyId(agentRecordDto.ParentCompanyId);
                        if (twoAgentRecordDto != null)
                        {
                            entity.TwoAgentRecordId = twoAgentRecordDto.AgentRecordId;
                            if (twoAgentRecordDto.ParentCompanyId != 1)
                            {
                                var oneAgentRecordDto = this.agentRecordService.GetByCompanyId(twoAgentRecordDto.ParentCompanyId);
                                if (oneAgentRecordDto != null)
                                {
                                    entity.OneAgentRecordId = oneAgentRecordDto.AgentRecordId;
                                }
                            }
                        }
                    }
                }
                else if (agentRecordDto.ParentCompanyId != 1)
                {
                    var oneAgentRecordDto = this.agentRecordService.GetByCompanyId(agentRecordDto.ParentCompanyId);
                    if (oneAgentRecordDto != null)
                    {
                        entity.OneAgentRecordId = oneAgentRecordDto.AgentRecordId;
                    }
                }
            }
        }
        #endregion


    }



}
